package com.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.exeception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.dimain.Question;
import com.tanhua.model.dimain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杰哥不要啦~
 * @date 2021/10/29
 */
@Service
public class TanhuaServer {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;

    @Autowired
    private HuanXinTemplate template;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MessagesService messagesService;

    //查询今日家人
    public TodayBest todayBest() {
        //获取用户id
        Long userid = UserHolder.getUserid();
        //调用api查询
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userid);
        //假如没有刷新出来,需要默认数据
        if (recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99d);
        }

        //3.将RecommendUser转换为TodayBest对象
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        TodayBest vo = TodayBest.init(userInfo,recommendUser);
        return vo;
    }

   // //分页查询推荐好友列表
   // public PageResult recommendation(RecommendUserDto dto) {
   //     //1、获取用户id
   //     Long userid = UserHolder.getUserid();
   //     //2、调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
   //     PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(),dto.getPagesize(),userid);
   //     //3、获取分页中的RecommendUser数据列表
   //     List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
   //     //4、判断列表是否为空
   //     if (items==null){
   //         return pr;
   //     }
   //     //5、循环RecommendUser数据列表，根据推荐的用户id查询用户详情
   //     List<TodayBest> list = new ArrayList<>();
   //     for (RecommendUser item : items) {
   //         Long recommendUserId = item.getUserId();
   //         UserInfo userInfo = userInfoApi.findById(recommendUserId);
   //         if (userInfo !=null){
   //             TodayBest vo = TodayBest.init(userInfo, item);
   //             list.add(vo);
   //         }
   //     }
   //     //6、构造返回值
   //     pr.setItems(list);
   //     return pr;
   // }
    //分页查询推荐好友列表
    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取用户id
        Long userid = UserHolder.getUserid();
        //2、调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(),dto.getPagesize(),userid);
        //3、获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //4、判断列表是否为空
        if (items==null){
            return pr;
        }
        //5、提取所有推荐的用户id列表
        List<Long> ids = CollUtil.getFieldValues(items, "userid", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        //6、构建查询条件，批量查询所有的用户详情
        Map<Long, UserInfo> map = userInfoApi.finByIds(ids, userInfo);
        //7、循环推荐的数据列表，构建vo对象
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info !=null){
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        //8、构造返回值
        pr.setItems(list);
        return pr;
        }

   //查询家人信息
    public TodayBest personalInfo(Long userId) {
        //1、根据用户id查询，用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、根据操作人id和查看的用户id，查询两者的推荐数据
        RecommendUser user = recommendUserApi.queryByUserId(userId,UserHolder.getUserid());
        return TodayBest.init(userInfo,user);
    }


    //查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question byUserId = questionApi.findByUserId(userId);
        return byUserId.getTxt()==null ? "哦~~~老baby!!!" :byUserId.getTxt();
    }

    //回复陌生人问题
    public void replyQuestions(Long userId, String reply) {
        //1、构造消息数据
        Long userid = UserHolder.getUserid();//获取当前用户id
        UserInfo userInfo = userInfoApi.findById(userid);//id查询当前用户信息
        Map map = new HashMap();//创建map集合
        map.put("userid",userid);
        map.put("huanXinId", Constants.HX_USER_PREFIX + userid);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",strangerQuestions(userId));
        map.put("reply",reply);
        String message = JSON.toJSONString(map);
        //2、调用template对象，发送消息
        Boolean aBoolean = template.sendMsg(Constants.HX_USER_PREFIX + userId, message);//1、接受方的环信id，2、消息
        //判断是否发送成功,没有成功抛出异常
        if(!aBoolean) {
            throw  new BusinessException(ErrorResult.error());
        }
    }

    //探花推荐卡片
    public List<TodayBest> queryCardsList() {
        //1、调用推荐API查询数据列表（排除喜欢/不喜欢的用户，数量限制）
        List<RecommendUser> users = recommendUserApi.queryCardsList(UserHolder.getUserid(),10);
        //2、判断数据是否存在，如果不存在，构造默认数据 1,2,3
        if (CollUtil.isEmpty(users)){
            users = new ArrayList<>();
            String[] userIds = recommendUser.split(",");
            for (String userId : userIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(UserHolder.getUserid());
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                users.add(recommendUser);
            }
        }
        //3、构造VO
        List<Long> ids = CollUtil.getFieldValues(users, "userId", Long.class);
        Map<Long, UserInfo> infomap = userInfoApi.finByIds(ids,null);

        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            UserInfo userInfo = infomap.get(user.getUserId());
            if (userInfo !=null){
                TodayBest vo = TodayBest.init(userInfo, user);
                vos.add(vo);
            }
        }
        return vos;
    }

    //探花喜欢
    public void likeUser(Long likeUserId) {
        //1、调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserid(), likeUserId, true);
        if (!save){
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        Long remove = redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + UserHolder.getUserid(), likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+UserHolder.getUserid(),likeUserId.toString());
        //3、判断是否双向喜欢
        if (isLike(likeUserId,UserHolder.getUserid())){
            //4、添加好友
            messagesService.contacts(likeUserId);
        }

    }
        //判断是否双向喜欢
    public Boolean isLike(Long userId,Long likeUserId){
        String key = Constants.USER_LIKE_KEY+userId;
        return redisTemplate.opsForSet().isMember(key,likeUserId.toString());//ismember,key是否在集合里面
    }


    //探花不喜欢
    public void notLikeUser(Long likeUserId) {
        //1、调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserid(), likeUserId, true);
        if (!save){
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserHolder.getUserid(), likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserid(),likeUserId.toString());
        //3、判断是否双向喜欢，删除好友(各位自行实现)
//        if (isLike(likeUserId,UserHolder.getUserid())){
//            //4、添加好友
//           // messagesService.contacts(likeUserId);
//        }
    }
}
